import time
import logging
from collections import defaultdict, deque
from models.register_model import Register


class DataProcessor:
    """Modbus数据处理类"""

    def __init__(self, modbus_protocol, config):
        self.modbus_protocol = modbus_protocol
        self.config = config

        # 初始化寄存器映射
        self.registers = self._load_register_config()
        self.register_groups = self._group_registers()

        # 数据历史记录
        self.data_history = defaultdict(lambda: deque(maxlen=100))

    def _load_register_config(self):
        """从配置加载寄存器映射"""
        registers = {}
        for reg_config in self.config.get_register_config():
            try:
                address = self.config.data_utils.hex_to_int(reg_config["address"])
                reg = Register(
                    address=address,
                    name=reg_config["name"],
                    unit=reg_config.get("unit", ""),
                    data_type=reg_config.get("type", "uint16"),
                    value=0
                )
                registers[address] = reg
            except KeyError as e:
                logging.error(f"寄存器配置错误: {str(e)}")
        return registers

    def _group_registers(self):
        """将连续地址的寄存器分组"""
        sorted_addresses = sorted(self.registers.keys())
        groups = []

        if not sorted_addresses:
            return groups

        # 创建连续地址组
        current_group = [sorted_addresses[0]]
        for i in range(1, len(sorted_addresses)):
            if sorted_addresses[i] == current_group[-1] + 1:
                current_group.append(sorted_addresses[i])
            else:
                groups.append(current_group)
                current_group = [sorted_addresses[i]]

        groups.append(current_group)
        return groups

    def poll_registers(self):
        """轮询所有寄存器"""
        for group in self.register_groups:
            start_addr = group[0]
            count = len(group)

            # 读取寄存器组
            values = self.modbus_protocol.read_holding_registers(start_addr, count)
            if values is None:
                continue

            # 更新寄存器值
            for i, addr in enumerate(group):
                if i < len(values):
                    # 更新寄存器值
                    self.registers[addr].value = values[i]

                    # 记录历史数据
                    self.data_history[addr].append((time.time(), values[i]))

    def get_register(self, address):
        """获取指定地址的寄存器"""
        return self.registers.get(address)

    def get_all_registers(self):
        """获取所有寄存器"""
        return list(self.registers.values())

    def get_register_value(self, address):
        """获取寄存器值"""
        reg = self.registers.get(address)
        return reg.value if reg else None

    def update_register_config(self, registers):
        """更新寄存器配置"""
        self.registers = registers
        self.register_groups = self._group_registers()
        self.data_history = defaultdict(lambda: deque(maxlen=100))